package th.retrofit.lib;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * https://leetcode-cn.com/problems/unique-binary-search-trees-ii/
 * 给你一个整数 n ，请你生成并返回所有由 n 个节点组成且节点值从 1 到 n 互不相同的不同 二叉搜索树 。可以按 任意顺序 返回答案。
 */
public class Solution95 {

    public List<TreeNode> generateTrees(int n) {
        if (n == 0) {
            return new LinkedList<TreeNode>();
        }
        return generateTrees(1, n);
    }

    public List<TreeNode> generateTrees(int start, int end) {
        List<TreeNode> allTrees = new LinkedList<TreeNode>();
        if (start > end) {
            allTrees.add(null);
            return allTrees;
        }

        // 枚举可行根节点
        for (int i = start; i <= end; i++) {
            // 获得所有可行的左子树集合
            List<TreeNode> leftTrees = generateTrees(start, i - 1);

            // 获得所有可行的右子树集合
            List<TreeNode> rightTrees = generateTrees(i + 1, end);

            // 从左子树集合中选出一棵左子树，从右子树集合中选出一棵右子树，拼接到根节点上
            for (TreeNode left : leftTrees) {
                for (TreeNode right : rightTrees) {
                    TreeNode currTree = new TreeNode(i);
                    currTree.left = left;
                    currTree.right = right;
                    allTrees.add(currTree);
                }
            }
        }
        return allTrees;
    }

    public List<TreeNode> generateTrees2(int n) {
        LinkedList<TreeNode>[] dp = new LinkedList[n + 1];
        if (n == 0) return new LinkedList<>();
        dp[0] = new LinkedList<>();
        dp[0].add(null);
        for (int i = 1; i <= n; i++) {
            dp[i] = new LinkedList<>();
            for (int j = 1; j <= i; j++) {
                int left = j - 1;
                int right = i - j;
                for (TreeNode leftTree : dp[left]) {
                    for (TreeNode rightTree : dp[right]) {
                        TreeNode treeRoot = new TreeNode(j);
                        treeRoot.left = leftTree;
                        treeRoot.right = clone(rightTree, j);
                        dp[i].add(treeRoot);
                    }
                }
            }
        }
        return dp[n];
    }

    private TreeNode clone(TreeNode source, int offset) {
        if (source == null) return null;
        TreeNode node = new TreeNode(source.val + offset);
        node.left = clone(source.left, offset);
        node.right = clone(source.right, offset);
        return node;
    }

    public static void main(String[] args) {
        List<TreeNode> results = new Solution95().generateTrees2(3);
        for (TreeNode node: results) {
            System.out.println(node);
        }
    }

}
